# ~*~ coding: utf-8 ~*~


def build_menu(menu_list, navigation=False):
    """
    构建菜单树
    :param menu_list:   权限列表
    :param navigation:  是否为导航
    :return:
    """
    # 生成菜单列表
    menus = []
    for menu_obj in menu_list:
        menu = {
            'id': menu_obj.id,
            'text': menu_obj.name,
            'pid': menu_obj.pid,

        }

        if navigation:
            module = menu_obj.module
            controller = menu_obj.controller
            action = menu_obj.action
            if module and controller and action:
                extension = {
                    'uri':  '/{0}/{1}/{2}/'.format(module, controller, action),
                    'icon': menu_obj.icon,
                    'class': '{0}-{1}-{2}'.format(module, controller, action)
                }
            elif module and controller:
                extension = {
                    'uri': '/{0}/{1}/'.format(module, controller),
                    'icon': menu_obj.icon,
                    'class': '{0}-{1}'.format(module, controller)
                }
            else:
                extension = {
                    'uri': 'javascript:void(0)',
                    'icon': menu_obj.icon,
                }
            menu.update(extension)
        menus.append(menu)

    # 生成菜单树
    menu_dict = {}
    for row in menus:
        # row.update({'nodes': []})
        menu_dict[row['id']] = row

    menu_tree = []
    for item in menus:
        if not item['pid']:
            menu_tree.append(item)
        else:
            if menu_dict.get(item['pid']):
                if 'nodes' not in menu_dict.get(item['pid']):
                    menu_dict.get(item['pid']).update({'nodes': []})
                menu_dict.get(item['pid'])['nodes'].append(item)

    return menu_tree
